<?php
namespace MyAdmin\Controller;

use Think\Controller;

class ModeController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index(){
    $page = I("page", 1);
    $page_size = I("page_size", 10);

    $list = M('mode')->where("is_delete = 0")->page($page.",".$page_size)->order('mode')->select();
    $this->assign('list',$list);
    $num = M('mode')->where("is_delete = 0")->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num);
    $this->assign("page_list", $page_list);
    $this->display('Apps/mode'); 
  }

  public function add(){
    $this->assign('select',home_url());
    $this->display('Apps/mode_add');
  }

  public function addSubmit(){
    $data = I('post.');
    $pic = file_upload($this->app_id)[0];
    $data['pic'] = $pic;
    
    if($data['url']==-1){
      if($data['link']=='' || $data['appid']==''){
         $this->error('参数错误',$_SERVER["HTTP_REFERER"]);
      }
      $data['url'] = $data['link'];
      $data['appid'] = $data['appid'];
    }else{
      $data['appid'] = '';
    }

    $data['openid'] = $this->app_id;
    $data['is_delete'] = 0;

    $insertId=M("mode")->data($data)->add();

    if($insertId){
      $this->success('新增成功',__APP__.'?m=MyAdmin&c=Mode&a=index');
    }else{
      $this->error('新增失败');
    }
  }

  public function edit($id){
    $list = M('mode')->where("id = $id")->find();

    $this->assign('list',$list);
    $this->assign('select',home_url());
    $option = '';
    foreach(home_url() as $v){
      if($v['route']==$list['url']){
        $option = $list['url'];
      }
    }

    $this->assign('option',$option);
    $this->display('Apps/mode_edit');
  }
  public function editSubmit(){
    $data = I('post.');
    $id = $data['id'];
    unset($data['id']);
    $pic = file_upload($this->app_id)[0];
    if($pic){
       $data['pic'] = $pic;
    }
    
    if($data['url']==-1){
      if($data['link']=='' || $data['appid']==''){
         $this->error('参数错误',$_SERVER["HTTP_REFERER"]);
      }
      $data['url'] = $data['link'];
      $data['appid'] = $data['appid'];
    }else{
      $data['appid'] ='';
    }
    unset($data['link']);
    $data['openid'] = $this->app_id;
    $model = M("mode");

    $insertId=$model->where("id=$id")->save($data);

    if($insertId){
      $this->success('编辑成功',__APP__.'?m=MyAdmin&c=Mode&a=index');
    }else{
      $this->error('编辑失败', $_SERVER["HTTP_REFERER"]);
    }
  }
  public function delete($id){
    if(is_numeric ($id)){
      $model = M('mode')->where("id = $id")->save(['is_delete'=>1]);
      $this->success('删除成功',__APP__.'?m=MyAdmin&c=Mode&a=index');
    }
  }

}
